var groupModule = function () {
    var editable = function () {
        return {
            init: function () {
                var oTable = $('#modelEditable').dataTable({
                    "lengthMenu": [
                        [10, 15, 20, 50, -1],
                        [10, 15, 20, 50, "All"]
                    ],
                    "autoWidth":false,
                    "scrollX": true,
                    "displayLength": 10,
                    "language": {
                        "lengthMenu": "每页 _MENU_ 条记录",
                        "paginate": {
                            "previous": "上一页",
                            "next": "下一页"
                        },
                        "info" : "从 _START_ 到  _END_ 条，总记录为 _TOTAL_ 条",    
                        "infoEmpty" : "记录数为0",
                    },
                    "columnDefs": [
						{
						    "data": null,
						    'sortable': false,
						    "defaultContent": "<center>-</center>",
						    "targets": [0]
						},
						{
						    "data": null,
						    'sortable': false,
						    "defaultContent": "<center>-</center>",
						    "targets": [1]
						}, 
						{
						    "data": null,
						    'sortable': false,
						    "defaultContent": "-",
						    "targets": [2]
						}            
                    ],
                    "columns": [
                       { "data": "name" },
                       { "data": "number" },
                   ],
                   "filter" : false,
                   "processing": false,
                   "serverSide": true,
                   "ajaxSource": ctx + "/investor/queryGroup",
                   "serverMethod": "post",
                   "fnRowCallback" : function(nRow, aData, displayIndex) {
                	   nRow.children[0].id = aData.id;
                	   nRow.children[0].number = aData.number;
                	   nRow.children[0].name = aData.name;
                	   $('td:eq(2)', nRow).html('<a class="lookfor fa fa-bars fa-lg " title="查看" href="javascript:;"></a>&nbsp;&nbsp;&nbsp;<a class="modify fa fa-pencil fa-lg " title="修改" href="javascript:;"></a>&nbsp;&nbsp;&nbsp;<a class="delete fa fa-times-circle-o fa-lg " title="删除" href="javascript:;"></a>');
                	   
                	   return nRow;
                   },
                   "fnServerData" : function(ajaxSource, dataSet, fnCallback) {
	                   var json = "";
	                   var s;
	                   for (var i = 0; i < dataSet.length; i++) {
	                       s = dataSet[i];
	                   	   if (s.name == 'sEcho') {
	                   		   json = json + '"echo":' + s.value;
		                   } else if (s.name == 'iDisplayStart') {
		                	   json = json + ',"page":' + s.value;
		                   } else if (s.name == 'iDisplayLength') {
		                	   json = json + ',"pageSize":' + s.value;
		                   }
	                   }
	                   var form = $("form#queryForm").serializeJSON();
                   	   var js = form.replace('}', ',');
                   	   json = js + json + "}";
                       $.ajax({
                       	   "contentType":"application/json; charset=UTF-8",
                           "dataType" : 'json',
                           "type" : "POST",
                           "url" : ctx + "/investor/queryGroup",
                           "data" : json,
                           "success" : fnCallback
                       });
                   },
                });
                // 删除分组
                $('#modelEditable').on("click", "a.delete", (function (e) {
                	 var nRow = $(this).parents('tr')[0];
                     var id = nRow.children[0].id;
                     var number = nRow.children[0].number;
                     if(number > 0){
                    	 bootbox.alert("无法删除分组人数大于零的分组");
                    	 return;
                     }
                	 $.teninedialog({
                         title:'系统提示',
                         content:'确认删除本条记录?',
                         showCloseButton:false,
                         otherButtons:["确定","取消"],
                         otherButtonStyles:['btn-primary','btn-white'],
                         bootstrapModalOption:{keyboard: true},
                         clickButton:function(sender,modal,index){
                        	 //删除投资人分组
                        	 if(index == 0){
                        		 json = "{\"id\":\""+id+"\"}";
                                 $.ajax({
                                 	 type:"post",
                                     contentType:"application/json; charset=UTF-8",
                                     url: ctx + "/investor/delGroup",
                                     data:json,
                                     dataType:"json",
                                     success: function(msg){
                                    	 $.teninedialog({
                                             title:'系统提示',
                                             content:msg.message,
                                             showCloseButton:false,
                                             otherButtons:["确定"],
                                             otherButtonStyles:['btn-primary'],
                                             bootstrapModalOption:{keyboard: true},
                                             clickButton:function(sender,modal,index){
                                             	location.reload();
                                             }
                                         });
                                     },
                                     error: function (msg) {
                                     	bootbox.alert("服务器出错了,删除分组失败了!");
                                     }
                                 });
                        	 }
                        	 $(this).closeDialog(modal); 
                         }
                     });
                }));
                // 查看
                $('#modelEditable').on("click", "a.lookfor", (function (e) {
                	 e.preventDefault();
                     var nRow = $(this).parents('tr')[0];
                     var id = nRow.children[0].id;
                     window.location.href = ctx +"/investor/list?groupId="+id;
                     return;
                }));
                // 修改
                $('#modelEditable').on("click", "a.modify", (function (e) {
                	e.preventDefault();
                	var nRow = $(this).parents('tr')[0];
                	var id = nRow.children[0].id;
                    var name = nRow.children[0].name;
                    $("#group_id").val(id);
                    $('#modify_group_name').val(name);
                    $('#old_group_name').val(name);
                    document.getElementById('modify_error_alert').style.display='none';
                	$('#modif_group').click();
                }));
                
                $('#btn_query').click(function(){
                	oTable.fnClearTable();
                });
            }

        };
    }();
    return {
        init: function () {
        	editable.init();
        }
    };
}();


var error = $('.alert-danger');
error.hide();
$('#btn_add_group').click(function(){
	var group_name = $('#group_name').val();
	if(group_name.length >10 || group_name.length <=0){
		error.show();
		return;
	}
	json = "{\"name\":\""+group_name+"\"}";
    var str = json;
    $.ajax({
    	type:"post",
        contentType:"application/json; charset=UTF-8",
        url: ctx + "/investor/addGroup",
        data:json,
        dataType:"json",
        success: function(msg){
        	$('#dsimiss_add_relation').click();
        	if(msg.code == 1){
        		showTips(msg.message,3000,true);
        	}else if(msg.code == 0){
        		showError(msg.message,3000,true);
        	}
        },
        error: function (msg) {
        	bootbox.alert(msg.message);
        }
    });
	
});

$('#btn_add_group_new').click(function(){
	var group_name = $('#group_name').val();
	if(group_name.length >10 || group_name.length <=0){
		error.show();
		return;
	}
	json = "{\"name\":\""+group_name+"\"}";
    var str = json;
    $.ajax({
    	type:"post",
        contentType:"application/json; charset=UTF-8",
        url: ctx + "/investor/addGroup",
        data:json,
        dataType:"json",
        success: function(msg){
        	if(msg.code == 1){
	        	$.teninedialog({
	                title:'系统提示',
	                content:msg.message,
	                showCloseButton:false,
	                otherButtons:["确定"],
	                otherButtonStyles:['btn-primary'],
	                bootstrapModalOption:{keyboard: true},
	                clickButton:function(sender,modal,index){
	                	 $(this).closeDialog(modal);
	                	 var data = msg.data;
	                	 var str = "";
	                	 for(var i = 0;i<data.length;i++){
	                		 str = str + "<option value=\""+data[i].id+"\"> "+data[i].name+"</option>"
	                	 }
	                	 $("#unselGroupId").html("");
	                	 $("#unselGroupId").html(str);
	                }
	            });
        	}else if(msg.code == 0){
        		bootbox.alert(msg.message);
        	}
        	$('#dsimiss_add_relation').click();
        },
        error: function (msg) {
        	bootbox.alert(msg.message);
        }
    });
	
});

$('#group_name').change(function(){
	var group_name = $('#group_name').val();
	if(group_name.length >10){
		error.show();
	}else{
		error.hide();	
	}
	
});

$('#add_group').click(function(){
	$('#group_name').val('');
	error.hide();	
});

$('#btn_modify_group').click(function(){
	var group_name = $('#modify_group_name').val();
	var size = group_name.length;
	var old_name = $('#old_group_name').val();
	var id = $('#group_id').val();
	if(size >10 || size <=0){
		document.getElementById('modify_error_alert').innerHTML='组别名称长度需在1到10个字符之间!';
		error_modify.show();
		return;
	}
	if(group_name == old_name){
		document.getElementById('modify_error_alert').innerHTML='新组名与旧组名相同!';
		error_modify.show();
		return;
	}
	json = "{\"id\":\""+id+"\",\"name\":\""+group_name+"\"}";
    var str = json;
    $.ajax({
    	type:"post",
        contentType:"application/json; charset=UTF-8",
        url: ctx + "/investor/modifyGroup",
        data:json,
        dataType:"json",
        success: function(msg){
        	$('#dsimiss_modify_relation').click();
        	$.teninedialog({
                title:'系统提示',
                content:msg.message,
                showCloseButton:false,
                otherButtons:["确定"],
                otherButtonStyles:['btn-primary'],
                bootstrapModalOption:{keyboard: true},
                clickButton:function(sender,modal,index){
                	location.reload();
                }
            });
        },
        error: function (msg) {
        	bootbox.alert(msg.message);
        }
    });
	
});
